// 该组件暂未用到
import * as React from "react";
import {
  Text,
  StyleSheet,
  View,
  ScrollView,
  Dimensions,
  Image
} from "react-native";

const { width } = Dimensions.get("window");

interface Props extends React.Props<any> {
  items: Array<any>;
  autoPlay: boolean;
}

interface State {
  currentIdx: number;
  offSetX: number;
}

export default class PageControl extends React.Component<Props, State> {
  private _scrollView: any;
  private _interval: any;

  constructor(props: Props) {
    super(props);
    this.state = {
      currentIdx: 0,
      offSetX: width
    };
  }

  render() {
    let pageDots = this.renderPagination();
    let contents = this.renderContent();
    return (
      <View style={styles.wrapper}>
        <ScrollView
          ref={(ref: any) => (this._scrollView = ref)}
          style={styles.scrollContent}
          pagingEnabled
          horizontal
          showsHorizontalScrollIndicator={false}
          showsVerticalScrollIndicator={false}
          bounces={false}
          keyboardDismissMode="on-drag"
          keyboardShouldPersistTaps="never"
          contentOffset={{ x: this.state.offSetX, y: 0 }}
          onScroll={(e: any) => this.scrollViewDidScroll(e)}
          onMomentumScrollEnd={(e: any) => this.onMomentumScrollEnd(e)}
          onScrollBeginDrag={(e: any) => this.scrollBeginDrag(e)}
          onScrollEndDrag={this.scrollEndDrag}
        >
          {contents}
        </ScrollView>
        {pageDots}
      </View>
    );
  }

  componentDidMount() {
    if (this.props.autoPlay === true) {
      this._autoPlayFunc();
    }
  }

  componentWillUnmount() {
    if (this.props.autoPlay === true) {
      clearInterval(this._interval);
    }
  }

  private renderPagination = () => {
    let dots: Array<any> = [];
    for (let i = 0; i < this.props.items.length; i++) {
      if (i === this.state.currentIdx) {
        const activeDot = <View style={styles.activeDotStyle} key={i} />;
        dots.push(activeDot);
      } else {
        const dot = <View style={styles.dotStyle} key={i} />;
        dots.push(dot);
      }
    }
    return (
      <View pointerEvents="none" style={styles.dotsStyle}>
        {dots}
      </View>
    );
  };

  private renderContent = () => {
    let contents: Array<any> = [];
    this.props.items.forEach((item: any, index: number) => {
      contents.push(
        <View style={styles.slide} key={index + 1}>
          <Image
            source={item.image}
            style={styles.image}
            resizeMode="stretch"
          />
          <Text style={styles.text}>{item.text}</Text>
        </View>
      );
    });
    // 首部插入一个
    contents.unshift(
      <View style={styles.slide} key={0}>
        <Image
          source={this.props.items[this.props.items.length - 1].image}
          style={styles.image}
          resizeMode="stretch"
        />
        <Text style={styles.text}>
          {this.props.items[this.props.items.length - 1].text}
        </Text>
      </View>
    );
    // 尾部插入一个
    contents.push(
      <View style={styles.slide} key={5}>
        <Image
          source={this.props.items[0].image}
          style={styles.image}
          resizeMode="stretch"
        />
        <Text style={styles.text}>{this.props.items[0].text}</Text>
      </View>
    );
    return contents;
  };

  // 动画结束后调用
  private onMomentumScrollEnd = (e: any) => {
    var offsetX = e.nativeEvent.contentOffset.x;
    var currentPage = Math.floor(offsetX / width);
    if (currentPage === 0) {
      this.setState({
        currentIdx: this.props.items.length - 1
      });
    } else if (currentPage === this.props.items.length + 1) {
      this.setState({
        currentIdx: 0
      });
    } else {
      this.setState({
        currentIdx: currentPage - 1
      });
    }
  };

  // 拖拽结束
  private scrollEndDrag = () => {
    if (this.props.autoPlay === true) {
      this._autoPlayFunc();
    }
  };

  // 拖拽开始
  private scrollBeginDrag = (e: any) => {
    if (this.props.autoPlay === true) {
      this.setState({ offSetX: e.nativeEvent.contentOffset.x });
      clearInterval(this._interval);
    }
  };

  private scrollViewDidScroll = (e: any) => {
    let setX = e.nativeEvent.contentOffset.x;
    if (setX === 0) {
      this.setState({
        offSetX: width * this.props.items.length
      });
    } else if (setX === width * (this.props.items.length + 1)) {
      this.setState({
        offSetX: width
      });
    } else {
      this.setState({
        offSetX: setX
      });
    }
  };

  private _autoPlayFunc = () => {
    this._interval = setInterval(() => {
      let setX = this.state.offSetX;
      setX += width;
      if (setX === 0) {
        setX = width * this.props.items.length;
      } else if (setX === width * (this.props.items.length + 1)) {
        setX = width;
      }
      //  page control
      var currentPage = Math.floor(setX / width);
      if (currentPage === 0) {
        this.setState({
          currentIdx: this.props.items.length - 1
        });
      } else if (currentPage === this.props.items.length + 1) {
        this.setState({
          currentIdx: 0
        });
      } else {
        this.setState({
          currentIdx: currentPage - 1
        });
      }
      this._scrollView.scrollTo({
        x: setX,
        y: 0,
        animated: true
      });
    }, 3000);
  };
}

const styles = StyleSheet.create({
  wrapper: {
    height: 240
  },
  scrollContent: {
    flex: 1
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "flex-start",
    backgroundColor: "transparent",
    width: width,
    height: "100%"
  },
  image: {
    width: "100%",
    flex: 1,
    height: 240
  },
  text: {
    position: "absolute",
    color: "white",
    bottom: 10,
    marginLeft: 20,
    marginRight: 70
  },
  pageStyle: {
    left: width - 90
  },
  dotStyle: {
    width: 5,
    height: 5,
    borderRadius: 3,
    backgroundColor: "rgba(255,255,255,.5)",
    marginLeft: 3,
    marginRight: 3,
    marginTop: 3,
    marginBottom: 3
  },
  activeDotStyle: {
    backgroundColor: "white",
    width: 8,
    height: 8,
    borderRadius: 4,
    marginLeft: 3,
    marginRight: 3,
    marginTop: 2,
    marginBottom: 3
  },
  dotsStyle: {
    position: "absolute",
    bottom: 10,
    right: 20,
    flexDirection: "row"
  }
});
